<template>
    <el-card class="box-card">
        <template #header>
            <!-- 调用关闭方法 -->
            <el-icon @click="$emit('close', true)">
                <ArrowLeftBold />
            </el-icon>
            <span>{{ option ? '新增' : '修改' }}</span>
        </template>
        <el-form label-position="right" label-width="100px" :model="myForm" style="max-width: 800px" ref="ruleFormRef"
            :rules="rules">
            <el-form-item label="封面图" prop="pic">
                <el-upload class="avatar-uploader" action="/dev-api/api/uploadimg/" :show-file-list="false"
                    :on-success="handleAvatarSuccess">
                    <img v-if="myForm.pic" :src="myForm.pic" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="标题" prop="title">
                <el-input v-model="myForm.title"></el-input>
            </el-form-item>
            <el-form-item label="展览时间" prop="exh_time">
                <el-date-picker v-model="myForm.exh_time" type="datetime" placeholder="请选择起始日期和时间" />
            </el-form-item>
            <el-form-item label="位置" prop="city">
                <el-input v-model="myForm.city"></el-input>
            </el-form-item>
            <el-form-item label="内容" prop="content">
                <input type="hidden" v-model="myForm.content">
                <div style="border: 1px solid #ccc">
                    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" />
                    <Editor style="height: 300px; overflow-y: hidden;" v-model="myForm.content"
                        @onCreated="handleCreated" />
                </div>
            </el-form-item>
            <el-form-item>
                <el-button @click="$emit('close', false)">取消</el-button>
                <el-button type="primary" @click="option ? addData(ruleFormRef) : updateData(ruleFormRef)">保存</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script setup>
import { Plus, ArrowLeftBold } from '@element-plus/icons-vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import service from '@/utils/request'
// 获取props中的数据
let props = defineProps({
    option: Boolean, // 用来判断是添加还是删除
    ChangeID: Number,
    FormData: Object, // 表达传递的数据
})
// 这是表单实例
const ruleFormRef = ref()
// 表单校验
const rules = reactive({
    pic: [
        { required: true, message: '请选择图片', trigger: 'change' },
    ],
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
    ],
    city: [
        { required: true, message: '请填写位置', trigger: 'blur' },
    ],
    exh_time: [
        { required: true, message: '请选择展览时间', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '请填写内容', trigger: 'blur' },
    ],
})
// 获取emit事件
const emit = defineEmits(['close'])
let myForm = ref({
    pic: '',
    title: '',
    city: '',
    exh_time: '',
    content: ''
})
// // 新增方法
// let addData = async () => {
//     myForm.value.exh_time = new Date(myForm.value.exh_time).toISOString().split('.')[0]
//     await service.post('/api/spread/spreadAdd', myForm.value)
//     emit('close', true)
// }
// 新增方法
let addData = async (formEl) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            myForm.value.exh_time = new Date(myForm.value.exh_time).toISOString().split('.')[0]
            await service.post('/api/spread/spreadAdd', myForm.value)
            emit('close', true)
        }
    })
}
// 修改方法
let updateData = async () => {
    myForm.value.exh_time = new Date(myForm.value.exh_time).toISOString().split('.')[0]
    await service.post(`/api/spread/spreadSet/${props.ChangeID}`, myForm.value)
    emit('close', true)
}
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// 内容 HTML
const valueHtml = ref('')
// 模拟 ajax 异步获取内容
onMounted(async () => {
    if (props.ChangeID) {
        let { data } = await service.get(`/api/spread/spreadSet/${props.ChangeID}`)
        myForm.value = data
    }
})
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

// 定义图片上传成功后返回图片并展示的函数
let handleAvatarSuccess = (e) => {
    myForm.value.pic = e.path
}
</script>


<style lang="scss" scoped>
.avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
    background-color: #f0f0f0;
}
</style>